package org.jeecg.modules.basicCompartment.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.basicCompartment.entity.BasicCompartment;
import org.jeecg.modules.basicCompartment.service.IBasicCompartmentService;
import org.jeecg.modules.basicShelf.entity.BasicShelf;
import org.jeecg.modules.system.util.QRCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

 /**
 * @Description: 货格表
 * @Author: jeecg-boot
 * @Date:   2023-11-01
 * @Version: V1.0
 */
@Api(tags="货格表")
@RestController
@RequestMapping("/basicCompartment/basicCompartment")
@Slf4j
public class BasicCompartmentController extends JeecgController<BasicCompartment, IBasicCompartmentService> {
	@Autowired
	private IBasicCompartmentService basicCompartmentService;
	
	/**
	 * 分页列表查询
	 *
	 * @param basicCompartment
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "货格表-分页列表查询")
	@ApiOperation(value="货格表-分页列表查询", notes="货格表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(BasicCompartment basicCompartment,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		String compartmentCode = basicCompartment.getCompartmentCode();
		basicCompartment.setCompartmentCode(null);
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		QueryWrapper<BasicCompartment> queryWrapper = QueryGenerator.initQueryWrapper(basicCompartment, req.getParameterMap());
		if (compartmentCode != null && !compartmentCode.isEmpty()){
			queryWrapper.like("compartment_code", compartmentCode);
		}
		queryWrapper.likeRight("sys_org_code", user.getOrgCode());
		queryWrapper.orderByAsc("create_time");
		Page<BasicCompartment> page = new Page<BasicCompartment>(pageNo, pageSize);
		IPage<BasicCompartment> pageList = basicCompartmentService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param basicCompartment
	 * @return
	 */
	@AutoLog(value = "货格表-添加")
	@ApiOperation(value="货格表-添加", notes="货格表-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody BasicCompartment basicCompartment) {
		basicCompartmentService.save(basicCompartment);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param basicCompartment
	 * @return
	 */
	@AutoLog(value = "货格表-编辑")
	@ApiOperation(value="货格表-编辑", notes="货格表-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody BasicCompartment basicCompartment) {
		basicCompartmentService.updateById(basicCompartment);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "货格表-通过id删除")
	@ApiOperation(value="货格表-通过id删除", notes="货格表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		basicCompartmentService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "货格表-批量删除")
	@ApiOperation(value="货格表-批量删除", notes="货格表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.basicCompartmentService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "货格表-通过id查询")
	@ApiOperation(value="货格表-通过id查询", notes="货格表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		BasicCompartment basicCompartment = basicCompartmentService.getById(id);
		if(basicCompartment==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(basicCompartment);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param basicCompartment
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BasicCompartment basicCompartment) {
        return super.exportXls(request, basicCompartment, BasicCompartment.class, "货格表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, BasicCompartment.class);
    }

	 /**
	  * 通过货架编码查询
	  *
	  * @param basicShelf
	  * @return
	  */
	 @AutoLog(value = "货格表-通过货架编码查询")
	 @ApiOperation(value="货格表-通过货架编码查询", notes="货格表-通过货架编码查询")
	 @PostMapping(value = "/getCompartment")
	 public Result<?> getCompartment(@RequestBody BasicShelf basicShelf) {
		 LambdaQueryWrapper<BasicCompartment> lqw = Wrappers.lambdaQuery(BasicCompartment.class);
		 lqw.eq(BasicCompartment::getShelfCode, basicShelf.getShelfCode());
		 List<BasicCompartment> compartments = basicCompartmentService.list(lqw);
		 if(compartments==null || compartments.size()==0) {
			 return Result.error("未找到对应数据");
		 }
		 return Result.OK(compartments);
	 }

	 //生成二维码并将其返回给前端调用者
	 @SneakyThrows
	 @GetMapping("/getQRCode")
	 public Result generateV2(@RequestParam(name = "compartment", required = true) String compartment, HttpServletResponse response) {
		 try (ServletOutputStream os = response.getOutputStream()) {
			 BufferedImage bufferedImage = QRCodeUtil.getQRCodeImage(compartment, false,
					 compartment);
			 try {
				 ImageIO.write(bufferedImage, "png", os);
			 } catch (IOException e) {
				 return null;
			 }
		 }
		 return Result.OK();
	 }

	 //生成二维码并将其返回给前端调用者
	 @SneakyThrows
	 @GetMapping("/getQRCodes")
	 public void generateV2s(@RequestParam(name = "ids", required = true) String ids, HttpServletResponse response) {
		 // 生成二维码图片
		 response.setContentType("application/octet-stream");
		 response.setHeader("Content-Disposition", "attachment; filename=" + System.currentTimeMillis() + ".zip");// 压缩包名
		 ZipOutputStream zos = null;
		 try {
			 zos = new ZipOutputStream(response.getOutputStream());
			 // zos.setLevel(5);//压缩等级
			 String[] arr = ids.split(",");
			 for (String id : arr) {
				 BasicCompartment compartment = basicCompartmentService.getById(id);
				 BufferedImage bufferedImage = QRCodeUtil.getQRCodeImage(compartment.getCompartmentCode(), false,
						 compartment.getCompartmentCode());
				 InputStream inputStream = bufferedImageToInputStream(bufferedImage);// 将bufferedImage转成inputStream
				 zos.putNextEntry(new ZipEntry(compartment.getCompartmentCode() + ".png")); // 压缩文件名称 设置ZipEntry对象
				 // zos.setComment("采样二维码"); // 设置注释
				 int temp = 0;
				 while ((temp = inputStream.read()) != -1) { // 读取内容
					 zos.write(temp); // 压缩输出
				 }
				 inputStream.close(); // 关闭输入流
			 }

		 } catch (Exception e) {
//			 return null;
		 } finally {
			 try {
				 if (null != zos) {
					 zos.flush();
					 zos.close();
				 }
			 } catch (IOException e) {
//				 return null;
			 }
		 }

//		 return Result.OK();
	 }

	 /**
	  * 将BufferedImage转换为InputStream
	  *
	  * @param image
	  * @return
	  */
	 public InputStream bufferedImageToInputStream(BufferedImage image) {
		 ByteArrayOutputStream os = new ByteArrayOutputStream();
		 try {
			 ImageIO.write(image, "png", os);
             return new ByteArrayInputStream(os.toByteArray());
		 } catch (IOException e) {
			 log.error("bufferedImageToInputStream方法出现异常：", e);
		 }
		 return null;
	 }

}
